package com.platform.modules.plug.controller;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.platform.common.aspectj.IgnoreAuth;
import com.platform.common.config.PlatformConfig;
import com.platform.common.constant.AppConstants;
import com.platform.common.constant.HeadConstant;
import com.platform.common.exception.BaseException;
import com.platform.common.shiro.ShiroLoginAuth;
import com.platform.common.shiro.ShiroUtils;
import com.platform.common.shiro.utils.Md5Utils;
import com.platform.common.shiro.vo.LoginUser;
import com.platform.common.utils.redis.RedisUtils;
import com.platform.common.version.ApiVersion;
import com.platform.common.version.VersionEnum;
import com.platform.common.web.domain.AjaxResult;
import com.platform.modules.auth.vo.AuthVo02;
import com.platform.modules.auth.vo.AuthVo03;
import com.platform.modules.chat.domain.ChatUser;
import com.platform.modules.chat.service.ChatUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 登录
 */
@RestController
@Slf4j
@RequestMapping("/open")
public class LoginController {

    @Resource
    private ChatUserService chatUserService;

    @Autowired
    private RedisUtils redisUtils;


    String LOGIN_FAIL_TIME = "plug:getToken:%s";

    /**
     * 获取token
     */
    @IgnoreAuth
    @ApiVersion(VersionEnum.V1_0_0)
    @PostMapping("/getToken")
    public AjaxResult getToken(@Validated @RequestBody AuthVo02 authVo) {

        String lock_key = AppConstants.LOCK_PREFIX + "token:" + authVo.getPhone();
        if (redisUtils.hasKey(lock_key)){
            throw new BaseException("操作太频繁，请稍后再试");
        }
        redisUtils.set(lock_key,authVo.getPhone(),AppConstants.LOCK_EXPIRE, TimeUnit.SECONDS);

        ChatUser chatUser = chatUserService.queryByPhone(authVo.getPhone());
        String payPassword = Md5Utils.credentials(authVo.getPassword(), chatUser.getSalt());
        String key = String.format(LOGIN_FAIL_TIME, authVo.getPhone());
        if (redisUtils.hasKey(key)) {
            throw new BaseException("获取失败，请稍后再试");
        }
        if (!StrUtil.equals(chatUser.getPassword(), payPassword)) {
            // 存入缓存
            redisUtils.set(key, chatUser.getNickName(), 5, TimeUnit.MINUTES);
            throw new BaseException("账号或密码错误");
        }


        if (redisUtils.hasKey(makeToken(chatUser.getToken()))){
            return AjaxResult.success(chatUser.getToken());
        }

        LoginUser loginUser = new LoginUser();
        loginUser.setToken(chatUser.getToken());
        loginUser.setUserId(chatUser.getUserId());
        loginUser.setPhone(chatUser.getPhone());

        // 存储redis
        redisUtils.set(makeToken(chatUser.getToken()), JSONUtil.toJsonStr(loginUser), PlatformConfig.TIMEOUT, TimeUnit.MINUTES);
        redisUtils.expire(lock_key,AppConstants.LOCK_END, TimeUnit.SECONDS);

        return AjaxResult.success(chatUser.getToken());
    }


    private String makeToken(String token) {
        return HeadConstant.TOKEN_REDIS_APP + token;
    }

}
